<template>
  <el-dialog
    title="佣金设置"
    class="setupdia"
    :visible.sync="syncCommissionDialog"
    width="530px"
  >
    <div class="setupcon">
      <el-form
        :model="privateSetUp"
        :rules="setUpRules"
        ref="ruleForm"
        label-position="left"
      >
        <el-form-item prop="pointMoney" class="setupcon__item setupcon__item1">
          <span>起提金额</span>
          <el-input
            :min="0"
            :controls="false"
            v-model="privateSetUp.pointMoney"
            class="setupcon__item1--input"
          >
            <template slot="append">元</template>
          </el-input>
          <span>满足起提金额部分才能提现</span>
        </el-form-item>
        <div class="setupcon__item setupcon__item2">
          <el-radio v-model="privateSetUp.type" :label="0">订单数</el-radio>
          <el-radio v-model="privateSetUp.type" :label="1">月结</el-radio>
        </div>
        <div
          v-if="privateSetUp.type === 0"
          class="setupcon__item setupcon__item3"
        >
          <div
            class="setupcon__item3--order"
            v-for="(item, i) in privateSetUp.orderNum"
            :key="i"
          >
            <span class="setupcon__item3--num1">{{ item.num[0] }}</span>
            <span class="setupcon__item3--tip1">-</span>
            <el-input
              :min="0"
              :controls="false"
              class="setupcon__item3--num2"
              v-model="item.num[1]"
              maxLength="7"
              @change="checkInteger(item.num[1])"
              placeholder="无穷大"
            >
            </el-input>
            <span class="setupcon__item3--tip2"><b>*</b>每单</span>
            <el-input
              :min="0"
              :controls="false"
              v-model="item.money"
              @change="checkOrderMonny(item.money)"
              class="setupcon__item3--money"
            >
              <template slot="append">元</template>
            </el-input>
            <el-button
              v-if="i !== 0"
              class="setupcon__item3--delete"
              @click="editOrderNumItem(i)"
              type="text"
              >删除
            </el-button>
          </div>
          <el-button
            class="setupcon__item3--addnew"
            type="text"
            @click="addOrderNumItem"
            >添加
          </el-button>
        </div>
        <el-form-item
          v-if="privateSetUp.type === 1"
          label="每月"
          label-width="40px"
          prop="monthPay"
          class="setupcon__item setupcon__item4"
        >
          <el-input
            :min="0"
            :controls="false"
            v-model="privateSetUp.monthPay"
            class="setupcon__item4--money"
          >
          </el-input
          >元
        </el-form-item>
      </el-form>
    </div>
    <div class="setupfooter">
      <el-button @click="syncCommissionDialog = false">取 消</el-button>
      <el-button type="primary" @click="savaData">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import {
  Vue,
  Component,
  Prop,
  Emit,
  Watch,
  PropSync,
  Ref,
} from "vue-property-decorator";

@Component({})
export default class CommissionSetUp extends Vue {
  /** 佣金设置弹框 */
  @PropSync("commissionDialog", { type: Boolean, default: false })
  syncCommissionDialog: boolean;

  @Prop()
  setUp: any;

  privateSetUp = {
    pointMoney: 0,
    type: 0,
    monthPay: 0,
    orderNum: [],
  };

  @Ref("ruleForm")
  refRuleForm;

  @Emit("emitSetUpData")
  emitSetUpData() {
    return this.privateSetUp;
  }

  @Watch("setUp", { immediate: true, deep: true })
  onSetUpChange(nval) {
    if (nval) {
      this.privateSetUp = JSON.parse(JSON.stringify(nval));
      const list = this.privateSetUp.orderNum || [];
      const length = list.length;
      if (length) {
        const temp = list[length - 1];
        // -1标识是无穷大，需要置空
        if (Number(temp.num[1]) === -1) {
          temp.num[1] = "";
        }
      } else {
        this.privateSetUp.orderNum = [
          {
            num: [0, ""],
            money: "",
          },
        ];
      }
    }
  }

  @Watch("syncCommissionDialog")
  syncCommissionDialogChange(val) {
    if (!val) {
      this.refRuleForm.resetFields();
    }
  }

  /**
   * 输入数值检测
   */
  validateMonthPay = (rule, value, callback) => {
    // 从接口拿到单会是数字类型，这里转一下
    value = String(value);
    const val = Number(value);
    if (Number.isNaN(val) || (value !== "0" && val === 0)) {
      callback(new Error("请输入数字值"));
    } else {
      const idx = value.indexOf(".");
      if (val < 0) {
        callback(new Error("数值最小为0"));
      } else if (idx !== -1 && value.length - idx > 3) {
        callback(new Error("最多两位小数"));
      } else {
        callback();
      }
    }
  };

  /**
   * 检测每月体现金额
   */
  validatePointMoney = (rule, value, callback) => {
    // 从接口拿到单会是数字类型，这里转一下
    value = String(value);
    const val = Number(value);
    if (Number.isNaN(val) || (value !== "0" && val === 0)) {
      callback(new Error("请输入数字值"));
    } else {
      const idx = value.indexOf(".");
      if (val < 0.3 || val > 5000) {
        callback(new Error("数值范围为0.3至5000"));
      } else if (idx !== -1 && value.length - idx > 3) {
        callback(new Error("最多两位小数"));
      } else {
        callback();
      }
    }
  };

  /**
   * 检测订单量
   */
  checkInteger(value) {
    // 从接口拿到单会是数字类型，这里转一下
    value = String(value);
    const val = Number(value);
    if (Number.isNaN(val) || val === 0) {
      this.$message.error("订单数只能输入数字且不能为0或空，请检查");
      return false;
    } else {
      const idx = value.indexOf(".");
      if (idx !== -1 || val < 1) {
        this.$message.error("订单数只能为正整数，请检查");
        return false;
      } else {
        return true;
      }
    }
  }

  /**
   * 检测每单金额
   */
  checkOrderMonny(value) {
    // 从接口拿到单会是数字类型，这里转一下
    value = String(value);
    const val = Number(value);
    if (Number.isNaN(val) || (value !== "0" && val === 0)) {
      this.$message.error("订单佣金只能输入数字且不能为空，请检查");
      return false;
    } else {
      const idx = value.indexOf(".");
      if (val < 0) {
        this.$message.error("订单佣金数值最小为0，请检查");
        return false;
      } else if (idx !== -1 && value.length - idx > 3) {
        this.$message.error("订单佣金最多两位小数，请检查");
        return false;
      } else {
        return true;
      }
    }
  }

  /** 校验规则 */
  setUpRules = {
    monthPay: [
      { validator: this.validateMonthPay, trigger: ["blur", "change"] },
    ],
    pointMoney: [
      { validator: this.validatePointMoney, trigger: ["blur", "change"] },
    ],
  };

  /**
   * 描述 编辑订单数
   * @param {any} idx: 序列号
   */
  editOrderNumItem(idx) {
    this.privateSetUp.orderNum.splice(idx, 1);
  }

  /**
   * 描述 新增订单数
   */
  addOrderNumItem() {
    const list = this.privateSetUp.orderNum;
    const length = list.length;
    const temp = list[length - 1];

    if (!length) {
      list.push({
        num: [0, ""],
        money: "",
      });
    } else {
      if (length === 20) {
        this.$message.error("最多添加20条");
        return false;
      }
      if (!this.checkInput(list)) {
        return false;
      }
      list.push({
        num: [Number(temp.num[1]) + 1, ""],
        money: Number(temp.money) + 1,
      });
    }
  }

  /**
   * 描述 输入合法性检测
   */
  checkInput(list) {
    let flag = true;

    for (const e of list) {
      if (!this.checkOrderMonny(e.money) || !this.checkInteger(e.num[1])) {
        flag = false;
        break;
      }
    }

    const tempList = JSON.stringify(list);
    let temp = JSON.parse(tempList).sort((a, b) => {
      return a.num[1] > b.num[1] ? 1 : -1;
    });
    temp = JSON.stringify(temp) === tempList;
    if (!temp) {
      this.$message.error("订单数填写不对， 请检查");
      flag = temp;
    }

    return flag;
  }

  async savaData() {
    const list = this.privateSetUp.orderNum;
    const tempList = JSON.parse(JSON.stringify(list));
    const temp = tempList[tempList.length - 1];
    const item = list[list.length - 1];
    const flag = temp.num[1] === "";
    // 不填默认是无穷大，这里设置一个值让检测通过
    if (flag) {
      temp.num[1] = 10000000;
    }
    if (Number(this.privateSetUp.type) === 0 && !this.checkInput(tempList)) {
      return false;
    }
    const checkList =
      Number(this.privateSetUp.type) === 0
        ? ["pointMoney"]
        : ["pointMoney", "monthPay"];
    let tips = true;
    this.refRuleForm.validateField(checkList, (valid) => {
      if (valid) {
        tips = false;
      }
    });
    if (tips) {
      if (flag) {
        item.num[1] = -1;
      }
      this.emitSetUpData();
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/logistics/pickPoint.scss";
</style>
<style lang="scss">
.setupcon__item1 {
  .el-form-item__error {
    padding-left: 75px !important;
  }
}
</style>
